<?php
/**
 * Created by PhpStorm.
 * User: zhangxilu
 * Date: 2017/12/27
 * Time: 下午11:29
 */

namespace common\logic;


use common\models\FavoriteModel;
use common\models\HouseModel;
use common\models\UserModel;
use yii\db\ActiveQuery;
use yii\helpers\ArrayHelper;

class FavoriteLogic extends Logic
{

    /**
     * @return ActiveQuery
     */
    protected function _getActiveQuery()
    {
        return FavoriteModel::find();
    }

    /**
     * 关注/取消关注
     *
     * @param $uid
     * @param $house_id
     * @param $status  0 取消，1 关注
     *
     * @return bool
     */
    public function favorite($uid, $house_id, $status)
    {

        $user = UserModel::findOne(['id' => $uid]);
        if(empty($user)){
            return '用户不存在';
        }


        $house = HouseModel::findOne(['id' => $house_id]);
        if(empty($house)){
            return '房源不存在';
        }

        try {
            $model = $this->_get(['uid' => $uid, 'house_id' => $house_id]);
            if ($status == 0) {
                if (!empty($model)) {

                    $model->delete();
                }
            } else {
                if (empty($model)) {
                    $model = new FavoriteModel();
                    $model->house_id = $house_id;
                    $model->uid = $uid;
                    $model->create_time = time();
                    $model->save();
                }
            }

            return true;
        } catch (\Throwable $exception) {
            return $exception->getMessage();
        }
    }


    public function getList($uid){
        $user = UserModel::findOne(['id' => $uid]);
        if(empty($user)){
            return '用户不存在';
        }
        $favoriteTable = FavoriteModel::tableName();
        /**
         * @var $data FavoriteModel[]
         */
        $data = $this->getQuery(["$favoriteTable.uid" => $uid])
            ->joinWith('house')
            ->orderBy(["$favoriteTable.create_time"=>SORT_DESC])
            ->limit(100)->all();

        $result = [];

        if (!empty($data)) {
            $hourseIds = ArrayHelper::getColumn($data, 'house_id');
            $images = HouseImageLogic::instance()->getFirstImage($hourseIds);

            foreach ($data as $k => $v) {

                $row =   ['create_time' => date('Y-m-d H:i:s', $v['create_time']), 'house_name'=> $v['house']['house_name'], 
                'id'=> $v['house']['id'], 'house_area'=> $v['house']['house_area'], 'house_unit_price'=> $v['house']['house_unit_price'], 
                'total_price'=> $v['house']['total_price'], 'address'=> $v['house']['address'], 'room1'=> $v['house']['room1'], 
                'room2'=> $v['house']['room2'], 'return_money'=> $v['house']['return_money'],'region_id'=> $v['house']['region_id']];

                $row['img_path'] = empty($images[$v['house_id']]) ? '' : $images[$v['house_id']];
                $result[] = $row;
            }

        }
        return ['list' => $result];
    }
}